package view;

import java.awt.*;
import java.awt.event.*;
import javax.sql.rowset.JdbcRowSet;
import javax.swing.*;

import data.*;

import java.util.Stack;

public class MineArea extends JPanel implements ActionListener, MouseListener {
    JButton reStart;
    Block[][] block;                  //雷区的方块
    BlockView[][] blockView;          //方块的视图
    LayMines lay;                      //负责布雷
    PeopleScoutMine peopleScoutMine;   //负责扫雷
    int row, colum, mineCount, markMount;//雷区的行数、列数以及地雷个数和用户给出的标记数
    ImageIcon mark;                   //探雷作的标记
    ImageIcon questionMark;       // 问号
    ImageIcon coverIcon; // 覆盖图片
    ImageIcon nullIcon; // 空图标
    String grade;                     //游戏级别
    JPanel pCenter, pNorth;            //布局用的面板
    JTextField showTime, showMarkedMineCount; //显示用时和探雷作的标记数目（不一定是雷哦）
    Timer time;                          //计时器
    int spendTime = 0;                     //扫雷的用时
    Record record;                       //负责记录到英雄榜
    PlayMusic playMusic;                 //负责播放雷爆炸的声音

    public MineArea(int row, int colum, int mineCount, String grade) {
        record = new Record(); //负责保存成绩到英雄榜
        reStart = new JButton("重新开始");
        mark = new ImageIcon("material/10.gif");  //探雷标记
        questionMark = new ImageIcon("material/15.png");
        coverIcon = new ImageIcon("material/9.gif");
        nullIcon = new ImageIcon("material/0.gif");
        time = new Timer(1000, this);                //计时器，每个一秒触发 ActionEvent 事件一次
        showTime = new JTextField(5);
        showMarkedMineCount = new JTextField(5);
        showTime.setHorizontalAlignment(JTextField.CENTER);
        showMarkedMineCount.setHorizontalAlignment(JTextField.CENTER);
        showMarkedMineCount.setFont(new Font("Arial", Font.BOLD, 16));
        showTime.setFont(new Font("Arial", Font.BOLD, 16));
        pCenter = new JPanel();
        pNorth = new JPanel();
        lay = new LayMines();                      //创建布雷者
        peopleScoutMine = new PeopleScoutMine(); //创建扫雷者
        initMineArea(row, colum, mineCount, grade); //初始化雷区，见下面的 initMineArea 方法
        reStart.addActionListener(this);
        pNorth.add(new JLabel("剩余雷数 (千万别弄错啊):"));
        pNorth.add(showMarkedMineCount);
        pNorth.add(reStart);
        pNorth.add(new JLabel("用时："));
        pNorth.add(showTime);
        setLayout(new BorderLayout());
        add(pNorth, BorderLayout.NORTH);
        add(pCenter, BorderLayout.CENTER);
        playMusic = new PlayMusic();              //负责播放触雷爆炸的声音
        playMusic.setClipFile("material/mine.wav");
        pCenter.setVisible(true);
        pNorth.setVisible(true);
        initShow();

    }

    public void initShow() {
        pCenter.setVisible(true);
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < colum; j++) {
                blockView[i][j].seeBlockCover(); //初始时盖住 block[i][j] 的数据信息
            }
        }
        repaint();
        validate();
    }

    public void initMineArea(int row, int colum, int mineCount, String grade) {
        pCenter.removeAll();
        spendTime = 0;
        markMount = mineCount;
        this.row = row;
        this.colum = colum;
        this.mineCount = mineCount;
        this.grade = grade;
        block = new Block[row][colum];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < colum; j++)
                block[i][j] = new Block();
        }
        lay.layMinesForBlock(block, mineCount);     //布雷
        peopleScoutMine.setBlock(block, mineCount); //准备扫雷
        blockView = new BlockView[row][colum];       //创建方块的视图
        pCenter.setLayout(new GridLayout(row, colum));
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < colum; j++) {
                blockView[i][j] = new BlockView();
                blockView[i][j].setCoverIcon(coverIcon);
                block[i][j].setBlockView(blockView[i][j]); //方块设置自己的视图
                blockView[i][j].setDataOnView();  //将 block[i][j] 的数据放入视图
                pCenter.add(blockView[i][j]);
                blockView[i][j].getBlockCover().addActionListener(this);//注册监视器
                blockView[i][j].getBlockCover().addMouseListener(this);
                //blockView[i][j].seeBlockCover(); //初始时盖住 block[i][j] 的数据信息
                blockView[i][j].getBlockCover().setEnabled(true);
                //blockView[i][j].getBlockCover().setIcon(null);
            }
        }

        showMarkedMineCount.setText("" + markMount);
        repaint();

    }

    public void setRow(int row) {
        this.row = row;
    }

    public void setColum(int colum) {
        this.colum = colum;
    }

    public void setMineCount(int mineCount) {
        this.mineCount = mineCount;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() != reStart && e.getSource() != time) {
            time.start();
            int m = -1, n = -1;
            for (int i = 0; i < row; i++) { //找到单击的方块以及它的位置索引
                for (int j = 0; j < colum; j++) {
                    if (e.getSource() == blockView[i][j].getBlockCover()) {
                        m = i;
                        n = j;
                        break;
                    }
                }
            }
            if (block[m][n].getIsMark() || block[m][n].getIsQuestionMark()) return; // 如果有标记则不应该执行操作
            if (block[m][n].isMine()) { //用户输掉游戏
                block[m][n].setMineIcon(new ImageIcon(new String("material/" + 12 + ".gif")));
                block[m][n].getBlockView().setDataOnView();
                for (int i = 0; i < row; i++) {
                    for (int j = 0; j < colum; j++) {
                        blockView[i][j].getBlockCover().setEnabled(false);//用户单击无效了
                        if (block[i][j].isMine())
                            blockView[i][j].seeBlockNameOrIcon(); //视图显示方块上的数据信息
                    }
                }
                time.stop();
                spendTime = 0;             //恢复初始值
                markMount = mineCount;      //恢复初始值
                playMusic.playMusic();    //播放类爆炸的声音

            } else {  //扫雷者得到 block[m][n] 周围区域不是雷的方块
                Stack<Block> notMineBlock = peopleScoutMine.getNoMineAroundBlock(block[m][n]);
                while (!notMineBlock.empty()) {
                    Block bk = notMineBlock.pop();
                    ViewForBlock viewforBlock = bk.getBlockView();
                    viewforBlock.setDataOnView();
                    viewforBlock.seeBlockNameOrIcon();//视图显示方块上的数据信息
                    if (bk.getIsMark()) --markMount;
                    //System.out.println("ookk");
                }
            }
        }
        if (e.getSource() == reStart) {
            initMineArea(row, colum, mineCount, grade);
            initShow();
            repaint();
            validate();
        }
        if (e.getSource() == time) {
            spendTime++;
            showTime.setText("" + spendTime);
        }
        if (peopleScoutMine.verifyWin(markMount)) {  //判断用户是否扫雷成功
            time.stop();
            record.setLocation(500, 400);
            record.setGrade(grade);
            record.setTime(spendTime);
            record.setVisible(true);       //弹出录入到英雄榜对话框
        }
    }

    public void mousePressed(MouseEvent e) { //探雷：给方块上插一个小旗图标（再次单击取消）
        JButton source = (JButton) e.getSource();
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < colum; j++) {
                if (e.getModifiers() == InputEvent.BUTTON3_MASK &&
                        source == blockView[i][j].getBlockCover()) {
                    if (block[i][j].getIsQuestionMark()) {
                        blockView[i][j].setCoverIcon(coverIcon);
                        blockView[i][j].seeBlockCover();
                        block[i][j].setIsQuestionMark(false);
                    } else if (block[i][j].getIsMark()) {
                        blockView[i][j].setCoverIcon(questionMark);
                        block[i][j].setIsMark(false);
                        block[i][j].setIsQuestionMark(true);
                        blockView[i][j].seeBlockCover();
                        markMount = markMount + 1;
                        showMarkedMineCount.setText("" + markMount);
                    } else {
                        blockView[i][j].setCoverIcon(mark);
                        block[i][j].setIsMark(true);
                        blockView[i][j].seeBlockCover();
                        markMount = markMount - 1;
                        showMarkedMineCount.setText("" + markMount);
                    }
                    blockView[i][j].seeBlockCover();
                }
            }
        }
    }

    public void mouseReleased(MouseEvent e) {
    }

    public void mouseEntered(MouseEvent e) {
    }

    public void mouseExited(MouseEvent e) {
    }

    public void mouseClicked(MouseEvent e) {
    }
}
